//
//  ProductShowController.m
//  cooba-iOS
//
//  Created by 郭四虎 on 16/4/19.
//  Copyright © 2016年 YouKu. All rights reserved.
//

#import "ProductShowController.h"
#import "ProductListCell.h"
#import "ProductModel.h"
#import "ProductExchangController.h"

typedef enum{
    proType_entity = 0,
    proType_virtual,
    proType_traffic
}proType;
@interface ProductShowController ()<UITableViewDelegate,UITableViewDataSource>
{
    UIButton *rightBtn;
    NSInteger nextkey;
}
@property (strong, nonatomic)UIView *menuView;
@property (strong, nonatomic)UIView *menu;
@property (weak, nonatomic) IBOutlet UITableView *table;
@property (strong, nonatomic) NSMutableArray *dataArr;

@end

@implementation ProductShowController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    nextkey = 0;
    [self initUI];
    [self createData:@{@"next_key":@(nextkey),@"page_size":@"10"}];
}

-(NSMutableArray *)dataArr
{
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}
- (UIView *)menu
{
    if (!_menu) {
        CGFloat width = 70;
        CGFloat height = 120;
        _menu = [[UIView alloc]initWithFrame:CGRectMake(WIDTH - width-5, 64, width, height)];
        _menu.layer.cornerRadius = 5;
        _menu.backgroundColor = [UIColor colorWithRed:238/255.0 green:238/255.0 blue:238/255.0 alpha:1];
        NSArray *arr = @[@"实物",@"虚拟",@"流量"];
        for (int i = 0; i<arr.count; i++) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(0, i*height/arr.count, width, height/arr.count-1);
            [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
            [btn setTitle:arr[i] forState:UIControlStateNormal];
            font(btn.titleLabel, 14);
            btn.tag = 600+i;
            [btn addTarget:self action:@selector(chooseKind:) forControlEvents:UIControlEventTouchUpInside];
            [_menu addSubview:btn];
            
            if (i != arr.count - 1) {
                UIView *line = [[UIView alloc]initWithFrame:CGRectMake(20, (i+1)*height/arr.count-1, width-40, 1)];
                line.backgroundColor = [UIColor lightGrayColor];
                [_menu addSubview:line];
            }
            
        }
    }
    return _menu;
}

- (UIView *)menuView
{
    if (!_menuView) {
        
        _menuView = [[UIView alloc]initWithFrame:self.view.bounds];
        
        [_menuView addSubview:self.menu];
    }
    return _menuView;
}

- (void)chooseKind:(UIButton *)btn
{
    [self.menuView removeFromSuperview];
    rightBtn.selected = !rightBtn.selected;
    
    proType type;
    switch (btn.tag-600) {
        case 0:{
            
            type = proType_entity;
            break;
        }
        case 1:{
            type = proType_virtual;
            break;
        }
        case 2:{
            type = proType_traffic;
            break;
        }
        default:
            break;
    }
    [self cleanData];
    nextkey = 0;
    NSDictionary *pra = @{@"type":@(type),@"next_key":@(nextkey),@"page_size":@"10"};
    [self createData:pra];
}

- (void)initUI
{
    self.title = @"兑换";
    rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setTitle:@"..." forState:UIControlStateNormal];
    [rightBtn setFrame:CGRectMake(0, 0, 50, 30)];
    [rightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    rightBtn.titleLabel.font =[UIFont fontWithName:@"AmericanTypewriter-Bold" size:17];
    [rightBtn setTitleEdgeInsets:UIEdgeInsetsMake(10, 30, 20, 0)];
    [rightBtn addTarget:self action:@selector(showMenu:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = right;
    
    [self.table delsetExtraline];
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.table registerNib:[UINib nibWithNibName:@"ProductListCell" bundle:nil] forCellReuseIdentifier:@"ProductListCell"];
    self.table.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
       
        [self cleanData];
        nextkey = 0;
        [self createData:@{@"next_key":@(nextkey),@"page_size":@"10"}];
    }];
    self.table.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        [self createData:@{@"next_key":@(nextkey),@"page_size":@"10"}];
    }];
}

- (void)cleanData
{
    [self.dataArr removeAllObjects];
    [self.table reloadData];
}

- (void)createData:(NSDictionary *)para
{
    if (nextkey == 10000) {
        Message(@"已经没有商品了");
        [self.table.footer endRefreshing];
        return;
    }
    [MyAFN POST:PRODUCTLIST parameters:para block:^(id responseObject) {
        [self.table.header endRefreshing];
        [self.table.footer endRefreshing];
        if ([[responseObject objectForKey:@"status"]integerValue]) {
            for (NSDictionary *dic in [responseObject objectForKey:@"productsList"]) {
                ProductModel *model = [[ProductModel alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                [self.dataArr addObject:model];
            }
            if (self.dataArr.count) {
                haveMessage(self.table);
               [self.table reloadData];
            }else{
                noMessage(self.table, @"暂时没有兑换信息");
            }
        }
        if ([[responseObject objectForKey:@"next_key"]integerValue]) {
            nextkey = [[responseObject objectForKey:@"next_key"]integerValue];
        }else{
            nextkey = 10000;
        }
    } error:^(NSError *error) {
        [self.table.header endRefreshing];
        [self.table.footer endRefreshing];
    } fromController:self];
}


- (void)showMenu:(UIButton *)btn
{
    if (!btn.selected) {
        [self.view addSubview:self.menuView];
    }else{
        [self.menuView removeFromSuperview];
    }
    btn.selected = !btn.selected;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ProductListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ProductListCell" forIndexPath:indexPath];
    ProductModel *model = self.dataArr[indexPath.row];
    [cell showModel:model];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100*SCALEY;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ProductModel *model = self.dataArr[indexPath.row];
    
    if (!model.num.integerValue) {
        [self.view Message:@"该物品已兑完"];
        return;
    }
    
    ProductExchangController *controller = [[ProductExchangController alloc]init];
    controller.model = model;
    controller.changeNum = ^{
        
        model.num = [NSString stringWithFormat:@"%ld",model.num.integerValue-1];
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    };
    [self.navigationController pushViewController:controller animated:YES];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *tou = [touches anyObject];
    
    if (tou.view != self.menu) {
        rightBtn.selected = !rightBtn.selected;
        [self.menuView removeFromSuperview];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
